/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: SignUpActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import io.bhex.app.utils.CustomerServiceUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.sdk.config.bean.IndexConfigBean;
import io.bhex.sdk.data_manager.RateAndLocalManager;
import io.bhex.app.R;
import io.bhex.sdk.account.bean.MobileCodeListBean;
import io.bhex.app.account.presenter.SignUpPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.constant.Fields;
import io.bhex.app.safe.DeepKnowVerify;
import io.bhex.app.safe.DeepSEListener;
import io.bhex.app.utils.ActivityCache;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.view.InputView;
import io.bhex.app.view.TopBar;
import io.bhex.app.web.ui.WebActivity;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;

/**
 * ================================================
 * 描   述：注册
 * ================================================
 */

public class SignUpActivity extends BaseActivity<SignUpPresenter, SignUpPresenter.SignUpUI> implements SignUpPresenter.SignUpUI, View.OnClickListener, CompoundButton.OnCheckedChangeListener, View.OnFocusChangeListener {
    private static final int VERIFY_REQUEST_CODE = 0x002;
    //默认是注册方式手机注册
    private boolean DEFULAT_SIGNUP_EMAIL = false;
    private Button registerBtn;
    private InputView accountEdt;
    private InputView pwdEdt;
    private InputView pwd2Edt;
    private InputView verifyCodeEdt;
    private InputView inviteCodeEdt;
    private TopBar topBar;
    private LinearLayout signupMobileCodeLinear;
    private TextView mobileCode;
    private CheckBox protocolCheckbox;
    private TextView sendVerifyCodeTv;
    private String caller = "";
    private DeepKnowVerify deepKnowVerify;
    private IndexConfigBean currentIndexConfig;

    @Override
    protected int getContentView() {
        return R.layout.activity_signup_layout;
    }

    @Override
    protected SignUpPresenter createPresenter() {
        return new SignUpPresenter();
    }

    @Override
    protected SignUpPresenter.SignUpUI getUI() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置禁止系统截屏、录制
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    }

    @Override
    protected void initView() {
        super.initView();
        deepKnowVerify = DeepKnowVerify.getInstance(this);
        Intent intent = getIntent();
        if (intent != null) {
            caller = intent.getStringExtra(AppData.INTENT.LOGIN_CALLER);
        }
        topBar = viewFinder.find(R.id.topBar);
        topBar.setRightText(getString(R.string.string_login));
        topBar.setRightTextAppearance(this, R.style.Body_Blue_Bold);
        topBar.setLeftImg(R.mipmap.icon_close);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.goLogin(SignUpActivity.this, caller);
            }
        });
        //默认邮箱注册
        signupMobileCodeLinear = viewFinder.find(R.id.signup_mobile_code_linear);
        viewFinder.textView(R.id.tab_a_name).setText(getString(R.string.string_email_register));
        viewFinder.textView(R.id.tab_b_name).setText(getString(R.string.string_mobile_register));
        registerBtn = viewFinder.find(R.id.btn_signup);
        mobileCode = viewFinder.find(R.id.signup_mobile_code);
        accountEdt = viewFinder.find(R.id.login_mobile_input);
        pwdEdt = viewFinder.find(R.id.login_pwd_input);
        pwd2Edt = viewFinder.find(R.id.login_pwd2_input);
        verifyCodeEdt = viewFinder.find(R.id.verify_code_et);
        verifyCodeEdt.setPaddingRight(PixelUtils.dp2px(80));
        sendVerifyCodeTv = viewFinder.textView(R.id.get_verify_code);
        inviteCodeEdt = viewFinder.find(R.id.invite_code_input);
        protocolCheckbox = viewFinder.find(R.id.signup_protocol_checkbox);
        accountEdt.setInputHint(getString(R.string.string_mobile_number));
        pwdEdt.setInputHint(getString(R.string.string_passwd));
        pwdEdt.setInputMode(InputView.PWDMODE);
        pwd2Edt.setInputHint(getString(R.string.string_passwd2));
        pwd2Edt.setInputMode(InputView.PWDMODE);
        verifyCodeEdt.setInputHint(getString(R.string.string_input_mobile_verify_code));
        inviteCodeEdt.setInputHint(getString(R.string.string_input_invite_code));
        signupMobileCodeLinear.setVisibility(View.VISIBLE);
        accountEdt.setPaddingLeft(PixelUtils.dp2px(68));
        setDefaultMobileCode();

    }

    private void setDefaultMobileCode() {
        String defaultMobileCode = CommonUtil.getDefaultMobileCode(this);
        if (!TextUtils.isEmpty(defaultMobileCode)) {
           mobileCode.setText("+"+defaultMobileCode);
        }
    }

    /**
     * 切换注册方式
     *
     * @param defulat_signup_email
     */
    private void switchSignupWay(boolean defulat_signup_email) {
        getPresenter().switchSignupWay(defulat_signup_email);
        accountEdt.setInputString("");
        pwdEdt.setInputString("");
        pwd2Edt.setInputString("");
        verifyCodeEdt.setInputString("");
        inviteCodeEdt.setInputString("");

        accountEdt.setError("");
        pwdEdt.setError("");
        pwd2Edt.setError("");
        verifyCodeEdt.setError("");
        inviteCodeEdt.setError("");
        if (defulat_signup_email) {
            DEFULAT_SIGNUP_EMAIL = false;

            accountEdt.setInputHint(getString(R.string.string_mobile_number));
            verifyCodeEdt.setInputHint(getString(R.string.string_input_mobile_verify_code));

            signupMobileCodeLinear.setVisibility(View.VISIBLE);
            accountEdt.setPaddingLeft(PixelUtils.dp2px(68));
        } else {
            DEFULAT_SIGNUP_EMAIL = true;
            accountEdt.setInputHint(getString(R.string.string_email));
            verifyCodeEdt.setInputHint(getString(R.string.string_input_email_verify_code));
            signupMobileCodeLinear.setVisibility(View.GONE);
            accountEdt.setPaddingLeft(PixelUtils.dp2px(8));
        }

    }

    /**
     * 设置tab
     *
     * @param isSetEmailLoginTab
     */
    private void setTab(boolean isSetEmailLoginTab) {
        if (isSetEmailLoginTab) {
            viewFinder.find(R.id.tab_a_indicator).setVisibility(View.VISIBLE);
            viewFinder.find(R.id.tab_b_indicator).setVisibility(View.GONE);
            viewFinder.textView(R.id.tab_a_name).setTextColor(getResources().getColor(R.color.blue));
            viewFinder.textView(R.id.tab_b_name).setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        } else {
            viewFinder.find(R.id.tab_a_indicator).setVisibility(View.GONE);
            viewFinder.find(R.id.tab_b_indicator).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.tab_a_name).setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
            viewFinder.textView(R.id.tab_b_name).setTextColor(getResources().getColor(R.color.blue));
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        registerBtn.setOnClickListener(this);
        viewFinder.find(R.id.signup_mobile_code_linear).setOnClickListener(this);
        viewFinder.find(R.id.get_verify_code).setOnClickListener(this);
        deepKnowVerify.ignoreDPView(viewFinder.find(R.id.get_verify_code),"SignUpActivity");
        viewFinder.find(R.id.signup_protocol).setOnClickListener(this);
        viewFinder.find(R.id.privacy_protocol).setOnClickListener(this);
        viewFinder.find(R.id.tab_a_rela).setOnClickListener(this);
        viewFinder.find(R.id.tab_b_rela).setOnClickListener(this);

        protocolCheckbox.setOnCheckedChangeListener(this);

        accountEdt.addTextWatch(mTextWatcher);
        pwdEdt.addTextWatch(mTextWatcher);
        pwd2Edt.addTextWatch(mTextWatcher);
        verifyCodeEdt.addTextWatch(mTextWatcher);
        pwdEdt.setOnFocusChangeListener(this);
        pwd2Edt.setOnFocusChangeListener(this);
    }

    @Override
    public void registerSuccess() {
        CustomerServiceUtils.setZendeskIdentify(this);
        if (caller.equals("")) {
            ActivityCache.getInstance().removeActivityFromCacheMap(this);
            ActivityCache.getInstance().finishActivity();
            IntentUtils.goMain(this);
            finish();
        }else if(caller.equals(AppData.INTENT.LOGIN_CALLER_WEB)||caller.equals(AppData.INTENT.LOGIN_CALLER_TRADE) || caller.equals(AppData.INTENT.LOGIN_CALLER_MAIN)){
            setResult(RESULT_OK);
            finish();
        }else{
            finish();
        }
    }

    @Override
    public void registerFailed(String reason) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.signup_mobile_code_linear:
                //选择国家区号
                IntentUtils.goMobileCodeList(this, Fields.REQUEST_CODE_SIGN_UP, Fields.FIELD_COUNTRY_PARAM_TYPE_AREA_CODE);

                break;
            //注册
            case R.id.btn_signup:
                getPresenter().signUp(DEFULAT_SIGNUP_EMAIL, mobileCode.getText().toString().replace("+", ""), accountEdt, pwdEdt, pwd2Edt, verifyCodeEdt, inviteCodeEdt, protocolCheckbox);

                break;
            //获取验证码
            case R.id.get_verify_code:

                final String account = accountEdt.getInputString();
                if (TextUtils.isEmpty(account)) {
                    ToastUtils.showShort(this, DEFULAT_SIGNUP_EMAIL ? getResources().getString(R.string.input_email) : getResources().getString(R.string.input_phone_number));
//                    accountEdt.setError(DEFULAT_SIGNUP_EMAIL ? getResources().getString(R.string.input_email) : getResources().getString(R.string.input_phone_number));
                    return;
                } else {
                    accountEdt.setError("");
                }
//                WebActivity.runActivityForResult(this, getString(R.string.string_check_is_people), Urls.H5_URL_RECAPTCHA, VERIFY_REQUEST_CODE);
                if (!NetWorkStatus.isConnected(this)) {
                    ToastUtils.showShort(this,getResources().getString(R.string.hint_network_not_connect));
                    return;
                }
                getUI().showProgressDialog("","");
                deepKnowVerify.verify(baseSEListener);
                break;
            case R.id.signup_protocol:
                if (currentIndexConfig != null) {
                    String userAgreement = currentIndexConfig.getUserAgreement();
                    if (!TextUtils.isEmpty(userAgreement)) {
                        WebActivity.runActivity(this, getString(R.string.string_signup_protocol), userAgreement);
//                        WebActivity.runActivity(this, getString(R.string.string_signup_protocol), Urls.H5_URL_REGISTER_SERVICE);
                    }
                }
                break;
            case R.id.privacy_protocol:
                String privacyAgreement = currentIndexConfig.getPrivacyAgreement();
                if (!TextUtils.isEmpty(privacyAgreement)) {
                    WebActivity.runActivity(this, getString(R.string.string_privacy_protocol), privacyAgreement);
//                    WebActivity.runActivity(this, getString(R.string.string_privacy_protocol), Urls.H5_URL_PRIVACY_POLICY);
                }
                break;
            case R.id.tab_a_rela:
                switchSignupWay(false);
                setTab(true);
                break;
            case R.id.tab_b_rela:
                switchSignupWay(true);
                setTab(false);
                break;
        }
    }

    private DeepSEListener baseSEListener = new DeepSEListener() {

        /**
         * SDK内部show loading dialog
         */
        @Override
        public void onShowDialog() {
            getUI().dismissProgressDialog();
        }

        @Override
        public void onError(String errorCode, String error) {
//            DebugLog.i(TAG,"onError-->errorCode:"+errorCode+", error: "+error);
//            ToastUtils.showShort(error);
            getUI().dismissProgressDialog();
            ToastUtils.showShort(getString(R.string.string_net_exception)+errorCode);
        }

        /**
         * 验证码Dialog关闭
         * 1：webview的叉按钮关闭
         * 2：点击屏幕外关闭
         * 3：点击回退键关闭
         *
         * @param num
         */
        @Override
        public void onCloseDialog(int num) {
//            DebugLog.i(TAG, "onCloseDialog-->" + num);
        }

        /**
         * show 验证码webview
         */
        @Override
        public void onDialogReady() {
            RateAndLocalManager.GetInstance(SignUpActivity.this).SetCurLocalKind(SignUpActivity.this,RateAndLocalManager.GetInstance(SignUpActivity.this).getCurLocalKind());

//            DebugLog.i(TAG,"onDialogReady-->SDK show captcha webview dialog! ");
        }

        /**
         * 验证成功
         * @param token
         */
        @Override
        public void onResult(String token) {
//            DebugLog.i(TAG,"onResult: "+token);
            //去二次验证
            getPresenter().verifyFirstRequest(DEFULAT_SIGNUP_EMAIL, mobileCode.getText().toString().replace("+", ""), accountEdt, token);
        }
    };

    @Override
    public boolean isChinaMobile() {
        return !DEFULAT_SIGNUP_EMAIL && mobileCode.getText().toString().equals("+86");
    }

    @Override
    public void showProtocolUrls(IndexConfigBean response) {
        currentIndexConfig = response;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        deepKnowVerify.destroy();
    }

    @Override
    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(accountEdt.getWindowToken(), 0);

    }

    @Override
    public void setAuthTv(String s) {
        sendVerifyCodeTv.setText(s);
    }

    @Override
    public void setAuthTvStatus(boolean b) {
        sendVerifyCodeTv.setEnabled(b);
        sendVerifyCodeTv.setTextColor(b ? getResources().getColor(R.color.blue) : SkinColorUtil.getDark50(this));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Fields.REQUEST_CODE_SIGN_UP && resultCode == RESULT_OK) {
            MobileCodeListBean.MobileCodeBean mobileCodeBean = (MobileCodeListBean.MobileCodeBean) data.getSerializableExtra(Fields.INTENT_MOBILE_CODE);
            if (mobileCodeBean != null) {
                String countryCode = mobileCodeBean.getNationalCode();
                if (!TextUtils.isEmpty(countryCode)) {
                    mobileCode.setText("+" + countryCode);
                }
            }
        } else if (requestCode == VERIFY_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                String token = data.getStringExtra("token");

                getPresenter().verifyFirstRequest(DEFULAT_SIGNUP_EMAIL, mobileCode.getText().toString().replace("+", ""), accountEdt, token);
            }
        }
    }

    /**
     * 编辑框监听器
     */
    private TextWatcher mTextWatcher = new TextWatcher() {

        /** 改变前*/
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        /** 内容改变*/
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            if (getPresenter().checkInputContentIsEmpty(DEFULAT_SIGNUP_EMAIL, mobileCode.getText().toString().replace("+", ""), accountEdt, pwdEdt, pwd2Edt, verifyCodeEdt, protocolCheckbox)) {
                viewFinder.find(R.id.btn_signup).setEnabled(true);
            } else {
                viewFinder.find(R.id.btn_signup).setEnabled(false);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }

    };

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//        if (getPresenter().checkInputContentIsEmpty(DEFULAT_SIGNUP_EMAIL, mobileCode.getText().toString().replace("+", ""), accountEdt, pwdEdt, pwd2Edt, verifyCodeEdt, protocolCheckbox)) {
//            if (isChecked) {
//                viewFinder.find(R.id.btn_signup).setEnabled(true);
//            } else {
//                viewFinder.find(R.id.btn_signup).setEnabled(false);
//            }
//
//        } else {
//            viewFinder.find(R.id.btn_signup).setEnabled(false);
//        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            getPresenter().checkPasswd(pwdEdt, pwd2Edt);
        }
    }
}
